package com.pig4cloud.pig.sthcloud.clients;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
public class TiandituReverseGeocodeClient {
	private static final String REVERSE_GEO_URL = "https://api.tianditu.gov.cn/geocoder";

//	private static final String apiKey = "ef5ad87ba7ba9c3fc5e92f7f549113bc";
	@Value("${tianditu.api.key}")
	private String apiKey;

	public Map<String, String> reverseGeocode(double latitude, double longitude) {
		try {
			// 1. 构造 postStr 的 JSON 字符串
			String postStr = String.format("{\"lon\":%.6f,\"lat\":%.6f}", longitude, latitude);
			// 调试用
//			System.out.println("原始 postStr: " + postStr);

			// 2. ✅ 必须进行 URL 编码（关键！）
			String encodedPostStr = URLEncoder.encode(postStr, StandardCharsets.UTF_8.toString());
			// 调试用
//			System.out.println("编码后 postStr: " + encodedPostStr);

			// 3. 构建完整 URL
			String url = REVERSE_GEO_URL +
					"?postStr=" + encodedPostStr +
					"&tk=" + apiKey +
					"&type=geocode";

			// 🚨 打印完整 URL 用于调试
//			System.out.println("请求 URL: " + url);

			// 4. 使用 GET 请求
			RestTemplate restTemplate = new RestTemplate();
			ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

//			System.out.println("HTTP 状态码: " + response.getStatusCode());
//			System.out.println("响应 body: " + response.getBody());

			if (response.getStatusCode() == HttpStatus.OK) {
				ObjectMapper mapper = new ObjectMapper();
				JsonNode root = mapper.readTree(response.getBody());

				// ✅ 重点：不要只看 status，要看 result 是否存在
				JsonNode resultNode = root.path("result");
				if (resultNode.isMissingNode() || resultNode.isNull()) {
//					System.err.println("天地图返回错误: 无结果数据，msg=" + root.path("msg").asText());
					// 🔐 安全返回空 Map
					return new HashMap<>();
				}

				// ✅ 即使 status="0"，只要 result 存在，就认为有数据
				Map<String, String> geoInfo = new HashMap<>();
				// 建议从 addressComponent 取值
				JsonNode ac = resultNode.path("addressComponent");

				geoInfo.put("province", ac.path("province").asText(""));
				geoInfo.put("city", ac.path("city").asText(""));
				geoInfo.put("district", ac.path("county").asText(""));
				geoInfo.put("town", ac.path("town").asText(""));
				geoInfo.put("street", ac.path("road").asText(""));
				geoInfo.put("formattedAddress", resultNode.path("formatted_address").asText(""));

//				System.out.println("解析成功: " + geoInfo);
				return geoInfo;

			} else {
				System.err.println("HTTP 请求失败: " + response.getStatusCode());
				return new HashMap<>();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
